package com.curry.log.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.curry.log.behavior.Behavior;
import com.curry.log.dervice.Device;




import android.os.Environment;

public class FileHelper {

	public static final String FOLDER_PATH = Environment
			.getExternalStorageDirectory() + "/orangelife/log/";
	public static final String FILE_SUFFIX=".json";
	/** 上传完成标记 **/
	private  final String OVER = "over_";
	/** 可以上传标记 **/
	private  final String FINSH = "finsh_";
	/** 可写入标记 **/
	private  final String OFFINE = "offine";
	
	public void saveLog(Behavior be,Device device){
		FileOutputStream fos=null;
		File file=new File(FOLDER_PATH);
		File newest_File=null;
		boolean key=false;
		boolean ishead=false;
		
		try {
			if(!file.exists()){
				file.mkdir();
			}
			/**判断是否是文件夹**/
			if(file.isDirectory()){
				/**返回最新的文件**/
				newest_File=newsetFile(file.listFiles());
				
				if(newest_File==null){
					key=true;
				}
				/**文件大于50K修改为待上传文件**/
				else if(newest_File.length()>=20*1024){
					fos=new FileOutputStream(newest_File, true);
					String end="]}";
					fos.write(end.getBytes("UTF-8"));
					fos.flush();
					key=true;
					newest_File.renameTo(new File(FOLDER_PATH+FINSH+newest_File.getName()) );
					fos.close();
				}
			}
			/**创建新文件**/
			if(key){
				newest_File= new File(FOLDER_PATH+OFFINE+device.getDeviceID()+(new Date()).getTime()+FILE_SUFFIX);
				if(!newest_File.createNewFile()){
					 throw new Exception();
				}
				
			}
			/**开启文件写入**/
			fos=new FileOutputStream(newest_File, true);
			/**文件内容为空写入头文件**/
			if(newest_File.length()==0){
				StringBuffer sb=new StringBuffer();
				sb.append("{");
				sb.append(JSONHelper.bean2json(device, JSONHelper.ACT_NO_HRED));

				sb.append("\"behavior\":[");
				fos.write(sb.toString().getBytes("UTF-8"));
				ishead=true;
			}
			String behavior=JSONHelper.bean2json(be, JSONHelper.ACT_OFF_HRED);
			if(ishead){
				fos.write(behavior.substring(1).getBytes("UTF-8"));
			}else{
				fos.write(behavior.getBytes("UTF-8"));
			}
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 返回子文件列表
	 * @param file
	 * @return
	 */
	
	private File newsetFile(File [] file){
		
		File []files=null;
		long modify_time = 0;
	    long tmp = 0;
	    File newest_File=null;
		files= file;
		
		for(int i=0;i<files.length;i++){
			modify_time = files[i].lastModified();
			String name=files[i].getName();
			if(name.indexOf(OVER)>-1){ 
				files[i].delete();
			}else{
				if(modify_time>tmp){		
					if(name.indexOf(FINSH)>-1){	
					}else{
						newest_File=files[i];
						tmp=modify_time;
					}
				}
			}
			
		}
		
		return newest_File;
	}
	/**
	 * 获取可以上传的文件，已 “_” 开头
	 * @return
	 */
	public String getUploadFiles(){
		
		File file=new File(FOLDER_PATH);
		StringBuffer sb=new StringBuffer();
	    File []files=null;
		if(file.isDirectory()){
			files=file.listFiles();
			for(int i=0;i<files.length;i++){
				String name=files[i].getName();
				if(name.indexOf(FINSH)>-1){
					if(name.indexOf(OVER)<0){ 
						sb.append("#"+files[i].getPath()); 
					}
				}else{
					if (name.indexOf(OFFINE) == 0) {
						
						FileOutputStream fos;
						try {
							fos = new FileOutputStream(files[i], true);
							String end = "]}";
							fos.write(end.getBytes("UTF-8"));
							fos.flush();
						} catch (Exception e) {
							e.printStackTrace();
						}
						files[i].renameTo(new File(FOLDER_PATH + FINSH
								+ files[i].getName()));
						sb.append("#" +FOLDER_PATH + FINSH
								+ files[i].getName());
					}
				}
				
			}
			if(sb.toString().length()>0){
				return sb.toString().substring(1);
			}else{
				return null;
			}
		}
		return null;
	}
	/**
	 * 将上传成功的文件名加上#符号
	 * @return
	 */
	public void removeFile(String path){
		File file=new File(path);
		if(file.exists()){
			file.renameTo(new File(file.getParent()+"/"+OVER+file.getName()));
		}
	}
}
